#ifndef VRP_GI_INCLUDED
#define VRP_GI_INCLUDED

#include "VBRDF.hlsl"
#include "VInput.hlsl"

struct GI
{
    float3 diffuse;
    float3 specular;
};

void sampleIBL(VInputData surface, VBRDFData brdf, out float3 giDiffuse, out float3 giSpecualr)
{
    
   
    float3 normal = surface.normalWS;
    
    float3 R = reflect(-surface.viewDirectionWS, normal);

    float NDoV=saturate(dot(normal, surface.viewDirectionWS));
    float3 F = fresnelSchlickRoughness(
        NDoV,
        brdf.fresnel0,
        brdf.roughness);
   
    
    //specularIBL
    // 用 R 来采样
    const float max_mitmap=7.0f;
    
    float roughness=0;
    roughness=brdf.roughness;
    float mip = roughness * (1.7 - 0.7 * roughness);
    float3 prefilteredColor = SAMPLE_TEXTURECUBE_LOD(IBL_lobeSpecularMap,my_Linear_clamp_sampler, R,mip).rgb;
    
    float3 scale_bias = SAMPLE_TEXTURE2D(IBL_BRDFMap,my_Linear_clamp_sampler,float2(NDoV,roughness)).rgb;
    float3 f_macro = F * scale_bias.x + scale_bias.y;
    #if defined(_MULTISCATTERING)
    float3 edgetint = float3(0.827, 0.792, 0.678);
    float3 F_avg = AverageFresnel(brdf.albedo,edgetint);
    
    float3 E_avg = SAMPLE_TEXTURE2D_LOD(MultiScattering_LUT_Avg,my_Linear_clamp_sampler,float2(0,roughness),0).rrr;

    // kulla-conty approximation
    
    
    float3 LoKc = brdf.fresnel0 * scale_bias.x + scale_bias.y;
    
    
    float3 intBrdfMs = F_avg * E_avg * (1 - LoKc) / (1 - F_avg * (1 - E_avg));
    
    
    f_macro += intBrdfMs;
    // if((intBrdfMs.x+intBrdfMs.y+intBrdfMs.z)>0.001)
    // {
    //     f_macro=0.0f;
    //     f_macro.x=1;
    // }
    #endif
    float3 Specular_Indirect=prefilteredColor * f_macro;
    
    float3 irradiance = SAMPLE_TEXTURECUBE_LOD(IBL_irradianceMap, my_Linear_clamp_sampler,normal,0).rgb;

    


    
    #ifdef _CLEARCOAT
    //roughness=0.5;
    roughness=brdf.clearCoatPerceptualRoughness;
    float3 coatIblF =fresnelSchlickRoughness(
        NDoV,
        brdf.fresnel0,
        brdf.clearCoatRoughness)*brdf.clearCoat;
    
    Specular_Indirect*=(1-coatIblF);
    float3 coatSpec = SAMPLE_TEXTURECUBE_LOD(IBL_lobeSpecularMap,my_Linear_clamp_sampler, R,roughness*max_mitmap).rgb;
    scale_bias = SAMPLE_TEXTURE2D(IBL_BRDFMap,my_Linear_clamp_sampler,float2(NDoV,roughness)).rgb;
    f_macro = coatIblF * scale_bias.x + scale_bias.y;
    coatSpec*=f_macro;
    Specular_Indirect += coatIblF * coatSpec;
    #endif
    
    giSpecualr = IBL_Intensity*Specular_Indirect;
    
//没乘kd
    giDiffuse =  IBL_Intensity*irradiance;

   

}

GI getGI( VInputData surface, VBRDFData brdf) {
    GI gi;
  
    gi.diffuse = 0.0f;
    gi.specular = 0.0f;
   
    sampleIBL(surface, brdf, gi.diffuse, gi.specular);
   

  

   

    
    return gi;
}


#endif